<script setup lang="ts">
import { ref } from 'vue'
import { Search, ArrowUp, ArrowDown, Edit, Delete } from '@element-plus/icons-vue'
import { assignUserRoleApi, getUserListApi, RemoveUserApi, updateUserApi } from '@/apis/login'
import type { UserRes } from '@/types/user'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormProps, FormItemProps } from 'element-plus'
import { checkMoible } from '@/utils/validate'
import type { RoleInfo } from '@/types/role'
import { getRoleListApi } from '@/apis/role'

const labelPosition = ref<FormProps['labelPosition']>('right')
const itemLabelPosition = ref<FormItemProps['labelPosition']>('')
let router = useRouter()
const formDate = ref({
  pagenum: 1,
  pagesize: 10,
  username: '',
  mobile: '',
  role_name: '',
  created_at: '',
  updated_at: '',
})
const total = ref(0)
const userList = ref([] as UserRes[])
const getUserList = async () => {
  const res = await getUserListApi(formDate.value)
  // console.log(res.data.list)
  userList.value = res.data.list as UserRes[]
  total.value = res.data.total as number
}
getUserList()

// 分页
// 每页显示最大发生改变
const handleSizeChange = (newSize: number) => {
  formDate.value.pagesize = newSize
  getUserList()
}
//处理页面发生改变
const handleCurrentChange = (newPage: number) => {
  formDate.value.pagenum = newPage
  getUserList()
}
// 重置表单
const resetForm = () => {
  formDate.value = {
    pagenum: 1,
    pagesize: 10,
    username: '',
    mobile: '',
    role_name: '',
    created_at: '',
    updated_at: '',
  }
  getUserList()
}

//添加功能
let addToCreate = () => {
  router.push('/user/create')
}
// 删除用户功能
let removeUser = async (userinfo: UserRes) => {
  // console.log(userinfo)

  const flag = await ElMessageBox.confirm('确定要删除该用户吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    // 响应成功在flag中,失败在catch中
  }).catch((error) => error)
  // 如何用户点击取消,就结束.否则就删除
  if (flag === 'cancel') return

  const res = await RemoveUserApi(userinfo)
  if (res.data.state !== 200) {
    return ElMessage.error(res.data.msg)
  }
  ElMessage.success('删除用户成功')
  // 重新调用获取用户数据
  getUserList()
}
// 筛选区收缩功能
let expend = ref(true)

// 用户编辑对话框
const editForm = ref()

// 自定义效验规则
const validateMobile = (rule: object, value: string, callback: (arg?: object) => void) => {
  if (checkMoible(value)) {
    callback()
  } else {
    callback(new Error('手机号不合法'))
  }
}
//表单效验
const formRules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ min: 6, max: 12, message: '密码长度在6~12位之间', trigger: 'blur' }],
  mobile: [{ validator: validateMobile, trigger: 'blur' }],
}

//获取角色列表
const roleList = ref([] as RoleInfo[])
const roleForm = ref({
  pagenum: 1,
  pagesize: 5,
  role_name: '',
})
const getRoleList = async () => {
  const res = await getRoleListApi(roleForm.value)
  roleList.value = res.data.list as RoleInfo[]
  // totalList.value = res.data.total as number
}
getRoleList()
// 用户编辑弹出框
let editUserVisible = ref(false)
const formRef = ref()
let editUser = (row: UserRes) => {
  //1.弹出框显示
  editUserVisible.value = true
  /*2.用户数据回显
      2.1可以通过作用域插槽传参的形式得到用户的信息(当前项目)
      2.2 可以通过用户id,发送ajax请求获取当前用户的数据
  */
  editForm.value = row
}
//3.用户更新
const updateUser = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    // ajax更新用户
    const res = await updateUserApi(editForm.value as UserRes)

    // 更新失败
    if (res.data.state !== 200) {
      ElMessage.error(res.data.msg)
    }

    // 更新成功
    ElMessage.success('更新成功')

    // 关闭对话框
    editUserVisible.value = false

    // 重新获取数据
    getUserList()
  })
}
// 重置数据并移除数据不合法提示
const resetEditUser = () => {
  formRef.value = {
    pagenum: 1,
    pagesize: 5,
    role_name: '',
  }
}

//弹出框关闭
const handleEditClose = () => {
  resetEditUser()
  resetEditRole()
}

// 角色编辑弹出框
const assignRoleFormRef = ref()
const assignUserRoleVisible = ref(false) //角色 弹出框是否显示
const assignRoleForm = ref({
  user_id: '',
  role_id: '',
  username: '',
  role_name: '',
})
const editRole = (row: any) => {
  //1.弹出框显示
  assignUserRoleVisible.value = true
  /*2.用户数据回显
      2.1可以通过作用域插槽传参的形式得到用户的信息(当前项目)
      2.2 可以通过用户id,发送ajax请求获取当前用户的数据
  */
  // assignRoleForm.value = row
  assignRoleForm.value.user_id = row.user_id
  assignRoleForm.value.role_id = row.role_id
  assignRoleForm.value.username = row.username
  assignRoleForm.value.role_name = row.role_name
}
// 立即更新
const assignUserRole = async () => {
  //1.ajax分配角色
  const res = await assignUserRoleApi(assignRoleForm.value)
  //2.关闭弹出框
  assignUserRoleVisible.value = false
  if (res.status !== 200) {
    ElMessage.error(res.data.msg)
    return
  }
  //3.消息提示
  ElMessage.success('分配角色成功')
  console.log(1)
  // 4.重新加载用户列表数据
  getUserList()
}
// 重置数据并移除数据不合法提示
const resetEditRole = () => {
  assignRoleFormRef.value = {
    user_id: '',
    role_id: '',
    username: '',
    role_name: '',
  }
}

//弹出框关闭
</script>

<template>
  <!-- 用户筛选区 -->
  <el-card style="max-width: 100%">
    <el-form :inline="true" :model="formDate">
      <el-form-item label="用户名">
        <el-input v-model="formDate.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="formDate.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="角色名" v-show="expend">
        <el-input v-model="formDate.role_name" placeholder="请输入角色名" />
      </el-form-item>
      <el-form-item label="创建于" v-show="expend">
        <el-date-picker
          v-model="formDate.created_at"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="default"
        />
      </el-form-item>
      <el-form-item label="更新于" v-show="expend">
        <el-date-picker
          v-model="formDate.updated_at"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="default"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getUserList">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetForm">重置</el-button>
      </el-form-item>
      <el-form-item @click="expend = !expend">
        <el-link type="primary" v-if="expend" :underline="false"
          >收缩 <el-icon style="margin-left: 5px"><ArrowUp /></el-icon
        ></el-link>
        <el-link type="primary" v-else :underline="false"
          >展开 <el-icon style="margin-left: 5px"><ArrowDown /></el-icon
        ></el-link>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 用户列表 -->
  <el-card style="max-width: 100%">
    <el-button type="danger">批量删除</el-button>
    <el-button type="primary" @click="addToCreate">添加</el-button>

    <el-table :data="userList" style="width: 100%" boder stripe>
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="user_id" label="编号" width="150" />
      <el-table-column prop="role_name" label="所属角色" width="120" />
      <el-table-column prop="avatar" label="头像" width="120">
        <!-- 作用域插槽  -->
        <template v-slot="slotScoped">
          <img
            :src="slotScoped.row.avatar"
            alt=""
            style="width: 30px; height: 30px; border-radius: 50%"
          />
        </template>
      </el-table-column>

      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="mobile" label="手机号" width="120" />
      <el-table-column prop="state" label="登录" width="120">
        <template v-slot="slotScoped">
          <!-- switch 开关 -->
          <el-switch
            v-model="slotScoped.row.state"
            style="--el--switch-on-color: #13ce66; --el--switch-off-color: #ff4949"
            active-value="1"
            inactive-value="0"
          />
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建于" width="120" />
      <el-table-column prop="updated_at" label="更新于" width="120" />
      <el-table-column fixed="right" label="操作" width="270">
        <template v-slot="{ row }">
          <el-button
            type="primary"
            :icon="Edit"
            size="small"
            @click="editUser(row)"
            v-auth="{ name: '用户编辑' }"
          />
          <el-button type="success" size="small" @click="editRole(row)">分配角色</el-button>
          <el-button
            type="danger"
            :icon="Delete"
            size="small"
            @click="removeUser(row)"
            v-auth="{ name: '用户删除' }"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 分页 -->
  <el-card style="max-width: 100%">
    <!-- size: 分页大小
     :page-sizes:每页显示条目个数
      :total:条目总数
     -->
    <el-pagination
      v-model:current-page="formDate.pagenum"
      v-model:page-size="formDate.pagesize"
      :page-sizes="[3, 5, 10, 20]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
  <!-- 编辑用户弹出框 -->
  <el-dialog v-model="editUserVisible" title="编辑用户" width="800" @close="handleEditClose">
    <el-form ref="formRef" :model="editForm" :rules="formRules" label-width="auto" size="large">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="editForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="editForm.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="editForm.mobile" placeholder="请输入手机号"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="updateUser">更新用户</el-button>
        <el-button @click="resetEditUser"> 重置 </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 角色编辑弹出框 -->
  <el-dialog v-model="assignUserRoleVisible" title="分配角色" width="500" @close="handleEditClose">
    <el-form :model="assignRoleForm" ref="assignRoleFormRef">
      <el-form-item label="当前用户">
        <el-input v-model="assignRoleForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="当前角色">
        <el-input v-model="assignRoleForm.role_name" disabled></el-input>
      </el-form-item>
      <el-form-item label="选择角色">
        <el-select v-model="assignRoleForm.role_id">
          <el-option
            :label="item.role_name"
            :value="item.role_id"
            :key="item.role_id"
            v-for="item in roleList"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="当前角色">
        <el-button type="primary" @click="assignUserRole">立即更新</el-button>
        <el-button @click="resetEditRole">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 10px;
}
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
